package service

import (
	"context"
	"errors"
	"time"

	"catering_sys_api/cmd/api/biz/business/model/login"
	"catering_sys_api/cmd/api/dao"
	"catering_sys_api/cmd/api/model"
	"catering_sys_api/cmd/api/pack/consts"
	"catering_sys_api/core/hash"
	"catering_sys_api/core/jwt"

	"github.com/cloudwego/hertz/pkg/app"
)

type LoginService struct {
	ctx context.Context
	c   *app.RequestContext
}

func NewLoginService(ctx context.Context, c *app.RequestContext) *LoginService {
	return &LoginService{
		ctx: ctx,
		c:   c,
	}
}

func (l *LoginService) PhoneLogin(request login.PhoneLoginRequest) (response login.PhoneLoginResponse, err error) {
	//登录的逻辑
	var (
		businessUserDao *dao.BusinessUserDao
		businessUser    *model.BusinessUser
	)

	businessUser = new(model.BusinessUser)

	businessUserDao = dao.NewBusinessUserDao(l.ctx)
	err = businessUserDao.GetBusinessUserByPhone(request.Phone, businessUser)

	if err != nil {
		return
	}
	//检查密码是否正确

	err = checkPwd(request.Password, businessUser)
	if err != nil {
		return
	}
	//生成token
	response.Token, err = genToken(businessUser)
	response.UserId = businessUser.ID
	response.RealName = businessUser.RealName
	response.Phone = businessUser.Phone
	response.BusinessID = businessUser.BusinessID
	if err != nil {
		return
	}
	//saveToken

	err = businessUserDao.SaveToken(businessUser.BusinessID, response.Token)
	if err != nil {
		return
	}

	return
}
func checkPwd(plaintextPassword string, businessUser *model.BusinessUser) (err error) {
	//检查密码验证次数
	if genPwd(plaintextPassword, businessUser.Salt) != businessUser.Password {
		err = errors.New("密码错误")
	}
	return
}
func genPwd(plaintextPassword, salt string) (ciphertextPassword string) {
	return hash.MD5V32(hash.MD5V32(plaintextPassword+salt) + salt)
}

func genToken(businessUser *model.BusinessUser) (token string, err error) {
	var customClaims jwt.CustomClaims
	customClaims.UserId = businessUser.ID
	customClaims.ExpiresAt = time.Now().Unix() * 2 * 3600
	token, err = jwt.GenToken(customClaims, consts.BusinessSecretKey)
	return
}
